package crm8000.services

import crm8000.Models.Goods;
import crm8000.Models.GoodsCategory;
import crm8000.Models.GoodsUnit;
import crm8000.helper.Result;
import grails.transaction.Transactional

@Transactional
class GoodsService {

	def allUnits() {
		return GoodsUnit.listOrderByName()
	}

	Result editUnit(params) {
		if (params.id) {
			// 编辑
			def u = GoodsUnit.countByNameAndIdNotEqual(params.name, params.id)
			if (u > 0) {
				return new Result(success: false, msg: "商品计量单位 [${params.name}] 已经存在")
			}

			def unit = GoodsUnit.findById(params.id)
			unit.name = params.name

			unit.save()
			return new Result(success: true, id: unit.id)
		} else {
			// 新增
			def u = GoodsUnit.countByName(params.name)
			if (u > 0) {
				return new Result(success: false, msg: "商品计量单位 [${params.name}] 已经存在")
			}

			def unit = new GoodsUnit(name: params.name)
			unit.save()
			return new Result(success: true, id: unit.id)
		}
	}

	Result deleteUnit(id) {
		def unit = GoodsUnit.findById(id)
		unit?.delete()

		return new Result(success: true)
	}

	def allCategories() {
		return GoodsCategory.listOrderByCode()
	}

	Result editCategory(params) {
		if (params.id) {
			// 编辑
			def c = GoodsCategory.countByCodeAndIdNotEqual(params.code, params.id)
			if (c > 0) {
				return new Result(success: false, msg: "编码为 ${params.code} 的商品分类已经存在")
			}
			def category = GoodsCategory.get(params.id)
			if (category) {
				category.code = params.code
				category.name = params.name
				category.save()

				return new Result(success: true, id: category.id)
			} else {
				return new Result(success: false, msg: "id为${params.id}的商品分类不存在")
			}
		} else {
			// 新增
			def c = GoodsCategory.countByCode(params.code)
			if (c > 0) {
				return new Result(success: false, msg: "编码为 ${params.code} 的商品分类已经存在")
			}

			def category = new GoodsCategory(code: params.code, name: params.name)
			category.save()
			return new Result(success: true, id: category.id)
		}
	}

	Result deleteCategory(id) {
		def category = GoodsCategory.get(id)

		if (!category) {
			return new Result(success: false, msg: "商品分类不存在")
		}

		def c = Goods.countByCategory(category)
		if (c > 0) {
			return new Result(success: false, msg: "当前分类下还有商品，不能删除")
		}

		category.delete()
		return new Result(success: true)
	}

	def goodsList(String categoryId) {
		return Goods.findAllByCategory(GoodsCategory.get(categoryId), [sort: 'code'])
	}
}
